//
// Created by Gorun on 2022/5/6.
//

#include "LoxInstance.h"

#include <utility>
#include "LoxClass.h"
#include "LoxFunction.h"
#include "Token.h"
#include "RuntimeError.h"

using namespace std;

LoxInstance::LoxInstance(shared_ptr<LoxClass> klass)
: klass{move(klass)}
{}

string LoxInstance::toString() {
    return klass->name + " instance";
}

any LoxInstance::get(const Token& name) {
    auto element = fields.find(name.lexeme);
    if (element!=fields.end()) {
        return fields[name.lexeme];
    }

    shared_ptr<LoxFunction> method = klass->findMethod(name.lexeme);
    if (method!=nullptr) return method->bind(shared_from_this());

    throw RuntimeError(name, "Undefined property '"+name.lexeme+"'.");
}

void LoxInstance::set(const Token &name, any value) {
    fields[name.lexeme]=move(value);
}

